import { createRouter, createWebHashHistory,createWebHistory } from 'vue-router'
import store from "@/store"

import approvals from './modules/approvals'
import attendances from './modules/attendances'
import departments from './modules/departments'
import employees from './modules/employees'
import permissions from './modules/permissions'
import salarys from './modules/salarys'
import settings from './modules/settings'
import social_securitys from './modules/social_securitys'
import user from './modules/user'
import { getToken } from '@/utils/auth'


// 动态路由

export const asyncRoutes=[
  approvals,
  attendances,
  departments,
  employees,
  permissions,
  salarys,
  settings,
  social_securitys,
  user
]

// 静态路由



export  const constantRoutes = [
  
  // 登陆
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
  },
  // 主页面
  {
    path: '/index',
    name: 'index',
    component: () => import('../views/index.vue'),
  },
  //以下为测试页面
  {
    path: '/about', 
    name: 'About',
    component: () => import(/* webpackChunkName: "About" */ '../views/About.vue')
  },
  {
    path: '/test',//vue3基本语法演示
    name: 'Test',
    component: () => import(/* webpackChunkName: "Test" */ '../views/Test.vue')
  },
   //根目录,到登录页面
   {
    path: '/',
    redirect: '/login'
  },
  //找不到页面到404,！！注意vue3里不能用*
  // {
  //  path: '/:catchAll(.*)',
  //  redirect: '/404'
  // }
]

const router = createRouter({
  history: createWebHashHistory(), // hash模式：createWebHashHistory，history模式：createWebHistory
  routes:[...constantRoutes]
})

// 访问的白名单, 可以直接通行
// 访问的白名单, 可以直接通行

router.beforeEach(async(to, from, next) => {
  // 访问的路径在白名单

  if(getToken()==null){
     if(to.path=='/login'){
      next()
     }else{
      next('/login')
     }
  }else{
    let a=await store.dispatch("getLists")
     // menus  存放的是后台传来的数据
     // const {menus}= a.data.roles
     // console.log(menus,59)
    //  if(!store.state.menuList.userId){
      let filterRoute =await store.dispatch('filterRouter',a.data.roles.menus)
             filterRoute.forEach(item=>{
               router.addRoute('index',{...item})
             })
    
      //  next(to.path)
    //  }else{
      next();
    //  }
  }
  //  if(to.path =='/login'){
  //   next();
  //  }else{
  //    if(store.state.userInfo==null){
  //     next("/login")
  //    }else{
  //     // const a= store.state.menuList
  //     let a=await store.dispatch("getLists")
  //     // menus  存放的是后台传来的数据
  //     // const {menus}= a.data.roles
  //     // console.log(menus,59);
  //     // if(store.state.arr.length==0){
  //       let filterRoute =await store.dispatch('filterRouter',a.data.roles.menus)
  //       filterRoute.forEach(item=>{
  //         router.addRoute('index',{...item})
  //       })
  //       // console.log(router,95);
  //       //  next({...to,replace:true})
  //     // }
  //     next();
  //    }
  //  }
})
export default router
